package com.treasure.web.interceptor;

import com.treasure.common.exception.AuthenticationException;
import com.treasure.common.model.SessionUser;
import com.treasure.common.model.SessionUserHolder;
import com.treasure.web.cache.SessionUserCache;
import com.treasure.web.service.LoginHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author sunhongmin
 * @date 2023/9/1 23:32
 * @description
 */
@Component
@Order(1)
public class AuthInterceptor extends LoginHelper implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader(TOKEN_HEADER_KEY);
        if (StringUtils.isBlank(token)) {
            // header未携带则再从cookie中获取一次
            String tokenFromCookie = getTokenFromCookie(request);
            if (StringUtils.isBlank(tokenFromCookie)) {
                throw new AuthenticationException("当前用户登录状态失效，请重新登录");
            } else {
                token = tokenFromCookie;
            }
        }

        SessionUser sessionUser = SessionUserCache.getCache(SESSION_TOKEN_KEY + token);
        if (Objects.isNull(sessionUser)) {
            throw new AuthenticationException("当前用户登录状态失效，请重新登录");
        }
        // 放入线程上下文
        SessionUserHolder.setSessionUser(sessionUser);
        // 缓存延期
        SessionUserCache.cacheDelay(SESSION_TOKEN_KEY + token);
        return true;
    }



    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        SessionUserHolder.clear();
    }
}
